﻿using MediatR;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.W.realize;

namespace MyMES.Read.API.Application.CommendHandlers.W.realize
{
    public class GetMaterialmanagementCommandHanders:IRequestHandler<GetMaterialmanagementCommands, APIPaging<List<Materialmanagement>>>
    {

        private readonly IBaseRepository<Materialmanagement> materialmanagementRepository;

        public GetMaterialmanagementCommandHanders(IBaseRepository<Materialmanagement> materialmanagementRepository)
        {
            this.materialmanagementRepository = materialmanagementRepository;
        }

        /// <summary>
        /// 显示物料产品管理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaging<List<Materialmanagement>>> Handle(GetMaterialmanagementCommands request, CancellationToken cancellationToken)
        {
            APIPaging<List<Materialmanagement>> result = new APIPaging<List<Materialmanagement>>();
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";
            var sql = "select * from Materialmanagement where IsDelete = false ORDER BY MId DESC";
            var list = await materialmanagementRepository.SelectAsync(sql);
            if (!string.IsNullOrEmpty(request.Materialname))
            {
                list = list.Where(x => x.Materialname.Contains(request.Materialname)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Materialnumber))
            {
                list = list.Where(x => x.Materialnumber.Contains(request.Materialnumber)).ToList();
            }
            result.TotalCount = list.Count;
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            list= list.Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            result.data= list;
            return result;
        }
    }
}
